import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_controller/components/customFijkPanel/customFijkPanel.dart';

class VideoCountListParam {
  String url;
  String title;
  VideoCountListParam({
    required this.url,
    required this.title,
  });
}

class Video extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _VideoState();
  }
}

class _VideoState extends State<Video> {
  FijkPlayer _player = FijkPlayer();

  /// 集数列表
  List<VideoCountListParam> _videoCountList = [];

  int _videoPlayIndex = 0;

  int seekTime = 0;

  bool isPlayAd = false;

  @override
  void initState() {
    for (var i = 0; i < 20; i++) {
      var url = "xxx/xxx.mp4";
      if (i % 2 == 0) {
        url = 'xxx.mp4';
      }
      _videoCountList.add(VideoCountListParam(
        url: url,
        title: "标题${i + 1}",
      ));
    }
    if (!isPlayAd) {
      setVideoUrl(_videoCountList[_videoPlayIndex].url);
    }
    super.initState();
  }

  @override
  void dispose() {
    _player.release();
    super.dispose();
  }

  Future<void> setVideoUrl(String url) async {
    try {
      await _player.setDataSource(url, autoPlay: true, showCover: true);
    } catch (error) {
      print("播放-异常: $error");
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQueryData = MediaQuery.of(context);
    double statusHeight = mediaQueryData.padding.top;
    Size size = mediaQueryData.size;
    double _videoHeight = size.width * 9 / 16;
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        body: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: statusHeight),
              color: Colors.black,
              child: FijkView(
                width: double.infinity,
                height: _videoHeight,
                player: _player,
                color: Colors.black,
                fsFit: FijkFit.contain, // 全屏模式下的填充
                fit: FijkFit.contain, // 正常模式下的填充
                panelBuilder:
                    (player, data, buildContext, viewSize, texturePos) {
                  return CustomFijkPanel(
                    player: player,
                    buildContext: context,
                    viewSize: viewSize,
                    texturePos: texturePos,
                    videoTitle: _videoCountList[_videoPlayIndex].title,
                    isPlayAd: isPlayAd,
                    isNextNumber: _videoPlayIndex + 1 < _videoCountList.length,
                    onPlayAd: () {
                      /// 播放广告 isPlayAd true 才会显示点击后处理播放后再开始播放视频
                    },
                    onError: () async {
                      await _player.reset();
                      setVideoUrl(_videoCountList[_videoPlayIndex].url);
                    },
                    onBack: () {
                      Navigator.pop(context); // 如果需要做拦截返回则在此判断
                    },
                    onVideoEnd: () async {
                      // 视频结束最后一集的时候会有个UI层显示出来可以触发重新开始
                      var index = _videoPlayIndex + 1;
                      if (index < _videoCountList.length) {
                        await _player.reset();
                        setState(() {
                          _videoPlayIndex = index;
                        });
                        setVideoUrl(_videoCountList[index].url);
                      }
                    },
                    onVideoTimeChange: () {
                      // 视频时间变动则触发一次，可以保存视频历史如不想频繁触发则在里修改 sendCount % 50 == 0
                    },
                    onVideoPrepared: () async {
                      // 视频初始化完毕，如有历史记录时间段则可以触发快进
                      try {
                        if (seekTime >= 1) {
                          /// seekTo必须在FijkState.prepared
                          await _player.seekTo(seekTime);
                          // print("视频快进-$seekTime");
                          seekTime = 0;
                        }
                      } catch (error) {
                        print("视频初始化完快进-异常: $error");
                      }
                    },
                  );
                },
              ),
            ),
            Container(
              width: 500,
              height: 50,
              margin: EdgeInsets.only(top: 15, bottom: 20, right: 10, left: 10),
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                // controller: _videoNumberController,
                padding: EdgeInsets.all(0),
                itemCount: _videoCountList.length,
                itemBuilder: (context, index) {
                  bool isCurrent = _videoPlayIndex == index;
                  Color textColor = Colors.black;
                  Color bgColor = Colors.white70;
                  Color borderColor = Colors.blueGrey;
                  if (isCurrent) {
                    borderColor = Colors.blue;
                    textColor = Colors.blue;
                    bgColor = Colors.transparent;
                  }
                  return GestureDetector(
                    onTap: () async {
                      await _player.reset();
                      setState(() {
                        _videoPlayIndex = index;
                      });
                      setVideoUrl(_videoCountList[index].url);
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: index == 0 ? 0 : 10),
                      width: 50,
                      height: 50,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        color: bgColor,
                        border: Border.all(
                          width: 1.5,
                          color: borderColor,
                        ),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        _videoCountList[index].title,
                        style: TextStyle(
                          fontSize: 15,
                          color: textColor,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
